import {Buffer}  from "buffer"
import CryptoJS from "crypto-js";
function fromHexString(hexString){
  return Buffer.from(hexString, 'hex');           
}
function uint8Array(uint8Array){
  return Array.prototype.map.call(uint8Array,(x)=>('00'+x.toString(16)).slice(-2)).join('');
}
//解密文件用的转16进制
function buf2hex(buffer) {
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' +
    x.toString(16)).slice(-2)).join('');
}
function isPureNumber(str) {
  const reg = /^[0-9]+$/; // 定义纯数字的正则表达式
  return reg.test(str); // 判断字符串是否符合正则表达式规则
}
//生成随机字符串
function randomWord(){
  var str = ""
  let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  for(let i=0; i<16; i++){
    let pos = Math.round(Math.random() * (arr.length-1));   
    str += arr[pos];
  }
  return str
}
//arraybuffer to wordarray 的转换函数
function swapendian32(val) {
  return (((val & 0xFF) << 24) | ((val & 0xFF00) << 8) | ((val >> 8) & 0xFF00) | ((val >> 24) & 0xFF)) >>> 0;
}
//arraybuffer转wordarray	
function arrayBufferToWordArray(arrayBuffer) {
  var fullWords = Math.floor(arrayBuffer.byteLength / 4);
  var bytesLeft = arrayBuffer.byteLength % 4;		
  var u32 = new Uint32Array(arrayBuffer, 0, fullWords);			
  var u8 = new Uint8Array(arrayBuffer);			
  var cp = [];			
  for (var i = 0; i < fullWords; ++i) {			
    cp.push(swapendian32(u32[i]));
  }
  if (bytesLeft) {
    var pad = 0;
    for (var i = bytesLeft; i > 0; --i) {
      pad = pad << 8;
      pad += u8[u8.byteLength - i];
    }
    for (var i = 0; i < 4 - bytesLeft; ++i) {
      pad = pad << 8;
    }
    cp.push(pad);
  }
  return CryptoJS.lib.WordArray.create(cp, arrayBuffer.byteLength);
}

export default {fromHexString,uint8Array,buf2hex,isPureNumber,randomWord,arrayBufferToWordArray}